// src/utils/errorHandler.ts
// import { useToast } from '@chakra-ui/react';
import { AppError } from './errorTypes';
import { createLogger } from './logger';
import { BrowserCompatibilityError } from './errorTypes';

const errorLogger = createLogger('error-handler');

/**
 * 错误处理服务
 */
export class ErrorHandler {
  private static instance: ErrorHandler;
  private toast: any = null;

  private constructor() {}

  static getInstance(): ErrorHandler {
    if (!ErrorHandler.instance) {
      ErrorHandler.instance = new ErrorHandler();
    }
    return ErrorHandler.instance;
  }

  /**
   * 设置 Toast 实例（需要在 React 组件中调用）
   */
  setToast(toast: any) {
    this.toast = toast;
  }

  /**
   * 处理应用错误
   */
  handleError(error: unknown, context?: string): void {
    // 记录错误日志
    this.logError(error, context);

    // 显示用户友好的错误提示
    this.showUserError(error);
  }

  /**
   * 记录错误到日志系统
   */
  private logError(error: unknown, context?: string): void {
    if (error instanceof AppError) {
      errorLogger.error(`[${error.code}] ${error.message}`, {
        context,
        severity: error.severity,
        recoverable: error.recoverable,
        stack: error.stack
      });
    } else if (error instanceof Error) {
      errorLogger.error(`Unknown error: ${error.message}`, {
        context,
        stack: error.stack
      });
    } else {
      errorLogger.error('Unknown error object:', { error, context });
    }
  }

  /**
   * 显示用户友好的错误提示
   */
  private showUserError(error: unknown): void {
    if (!this.toast) {
      console.warn('Toast not initialized, cannot show error message');
      return;
    }

    let title = '发生错误';
    let description = '请重试或联系支持';
    let status: 'error' | 'warning' | 'info' = 'error';
    let duration: number | undefined = 5000; // ✅ 显式声明联合类型
    let isClosable = true;

    if (error instanceof AppError) {
      title = this.getErrorTitle(error.severity);
      description = error.userMessage;
      status = this.getToastStatus(error.severity);
      duration = error.recoverable ? 5000 : undefined; // 不可恢复的错误不自动关闭
    } else if (error instanceof Error) {
      description = '系统发生未知错误，请刷新页面重试';
    }

    this.toast({
      title,
      description,
      status,
      duration,
      isClosable,
      position: 'top-right'
    });
  }

  /**
   * 根据错误严重程度获取 Toast 标题
   */
  private getErrorTitle(severity: 'low' | 'medium' | 'high'): string {
    switch (severity) {
      case 'low': return '提示';
      case 'medium': return '需要注意';
      case 'high': return '严重错误';
      default: return '发生错误';
    }
  }

  /**
   * 根据错误严重程度获取 Toast 状态
   */
  private getToastStatus(severity: 'low' | 'medium' | 'high'): 'error' | 'warning' | 'info' {
    switch (severity) {
      case 'low': return 'info';
      case 'medium': return 'warning';
      case 'high': return 'error';
      default: return 'error';
    }
  }

  /**
   * 检查浏览器兼容性
   */
  checkBrowserCompatibility(): void {
    const missingFeatures: string[] = [];

    // 检查 Canvas 支持
    if (!window.HTMLCanvasElement) {
      missingFeatures.push('Canvas');
    }

    // 检查 FileReader 支持
    if (!window.FileReader) {
      missingFeatures.push('FileReader');
    }

    // 检查必要的 Canvas API
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    if (!ctx) {
      missingFeatures.push('Canvas 2D Context');
    }

    if (missingFeatures.length > 0) {
      const error = new BrowserCompatibilityError(missingFeatures.join(', '));
      this.handleError(error, 'browser-compatibility-check');
    }
  }
}

// 导出单例实例
export const errorHandler = ErrorHandler.getInstance();
